package com.learn.english.mapper;

import com.learn.english.model.entity.Note;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface NoteMapper {

    @Select("SELECT * FROM note WHERE id = #{id}")
    Note selectById(Integer id);

    @Select("SELECT * FROM note WHERE user_id = #{userId} ORDER BY id ASC")
    List<Note> selectByUserId(Integer userId);

    @Select("SELECT * FROM note ORDER BY id ASC")
    List<Note> selectAll();

    @Select({
            "<script>",
            "SELECT * FROM note",
            "WHERE 1=1",
            "<if test='userId != null'>AND user_id = #{userId}</if>",
            "<if test='title != null and title != &quot;&quot;'>AND title LIKE CONCAT('%', #{title}, '%')</if>",
            "ORDER BY id ASC",
            "LIMIT #{offset}, #{limit}",
            "</script>"
    })
    List<Note> selectWithPagination(
            @Param("userId") Integer userId,
            @Param("title") String title,
            @Param("offset") int offset,
            @Param("limit") int limit
    );

    @Select({
            "<script>",
            "SELECT COUNT(*) FROM note",
            "WHERE 1=1",
            "<if test='userId != null'>AND user_id = #{userId}</if>",
            "<if test='title != null and title != &quot;&quot;'>AND title LIKE CONCAT('%', #{title}, '%')</if>",
            "</script>"
    })
    long count(@Param("userId") Integer userId, @Param("title") String title);

    @Insert({
            "INSERT INTO note (user_id, title, content, parent_id)",
            "VALUES (#{userId}, #{title}, #{content}, #{parentId})"
    })
    @Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
    void insert(Note note);

    @Update({
            "<script>",
            "UPDATE note",
            "SET user_id = #{userId}, title = #{title}, content = #{content}",
            "<if test='parentId != null'>, parent_id = #{parentId}</if>",
            "<if test='parentId == null'>, parent_id = NULL</if>",
            "WHERE id = #{id}",
            "</script>"
    })
    int updateById(Note note);

    @Delete({
            "<script>",
            "DELETE FROM note WHERE id IN",
            "<foreach collection='ids' item='id' open='(' separator=',' close=')'>",
            "#{id}",
            "</foreach>",
            "</script>"
    })
    void deleteByIds(@Param("ids") List<Integer> ids);
}